package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.ICreationAwardService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CKQ
 * @DateTime: 2020/5/26 19:34
 * @Description: TODO
 */
@Slf4j
@Service
public class CreationAwardServiceImpl  implements ICreationAwardService {
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private HttpService httpService;

    @Autowired
    private CustomerService customerService;


    //绑定营销号
    @Override
    public  Boolean bindMarketingAccount(String customerId,String orgId, String userCode, String pwd){
        //如果用户名和密码多为空 则直接解绑
        if(StringUtils.isEmpty(userCode) && StringUtils.isEmpty(pwd)){
           return customerService.updateMarketingAccountByCustomerId(customerId, "");
        }
        String userId = this.verificationCasAccount(userCode, pwd,orgId);
        if(StringUtils.isEmpty(userId)){
            throw GlobalException.build("账号密码错误，请重试");
        }

        //获取营销账号
        String marketingAccount = this.getMarketingAccount(userId,orgId);
        if(StringUtils.isEmpty(marketingAccount)){
            throw GlobalException.build("此账号未创建营销号账号");
        }
        if(customerService.isExitMarketingAccountCustomer(marketingAccount,orgId)) {
            throw GlobalException.build("此融媒账号已绑定其他账号");
        }
        //绑定
       if( !customerService.updateMarketingAccountByCustomerId(customerId,marketingAccount)) {
           throw GlobalException.build("绑定营销号账号失败，请重试");
       }
       return  true;
    }
    @Override
    public String getMarketingName(String marketingAccount){
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("rmhid", marketingAccount);
        String url = systemProperties.getAwakenlabelurl() + "/Service/rmh/info/id";
        String result = "";
        try {
            result = httpService.doGet(url, reqMap);
        } catch (URISyntaxException | IOException e) {
            throw GlobalException.build("获取营销号失败，请重试");
        }
        if (!StringUtils.isEmpty(result)) {
            Map parse = (Map) JSON.parse(result);
            if((Integer) parse.get("code") == 0){
                String name = "";
                JSONArray datalist = JSON.parseArray(parse.get("data").toString());
                if(datalist!=null && datalist.size()>0){
                    for (Object item : datalist) {
                        if (item != null) {
                            JSONObject obj = JSON.parseObject(item.toString());
                            name = obj.get("name").toString();
                            continue;
                        }
                    }
                }
                return  name;
            }
            return  "";
        } else {
            return "";
        }
    }

    //调用用户中心验证账号密码获得userid
    @Override
    public String verificationCasAccount(String userCode, String pwd,String orgCode) {
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("usercode", userCode);
        reqMap.put("pwd",  DigestUtils.md5DigestAsHex(pwd.getBytes()));
        reqMap.put("orgcode",orgCode);
        String url = systemProperties.getManageweb() + "/UserWebApi/api/user/info";
        String result = "";
        try {
            result = httpService.doGet(url, reqMap);
        } catch (URISyntaxException | IOException e) {
            throw GlobalException.build("验证账号失败，请重试");
        }
        if (!StringUtils.isEmpty(result)) {
            Map<String, Object> parse = ( Map<String, Object>) JSON.parseObject(result);
            if((Integer) parse.get("retcode") == 0){
                return JSON.parseObject(parse.get("retobj").toString()).get("userid").toString();
            }else{
                return "";
            }
        } else {
            return "";
        }
    }

    //获取营销账号
    @Override
    public String getMarketingAccount(String userId,String orgCode){
        try {
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("userid", userId);
            reqMap.put("orgcode", orgCode);
            String url = systemProperties.getAwakenlabelurl() + "/Service/rmh/info";
            String result = "";
            result = httpService.doGet(url, reqMap);
            if (!"".equals(result)) {
                Map parse = (Map) JSON.parse(result);
                if ((Integer) parse.get("code") == 0) {
                    String id = "";
                    JSONArray datalist = JSON.parseArray(parse.get("data").toString());
                    if (datalist != null && datalist.size() > 0) {
                        for (Object item : datalist) {
                            if (item != null) {
                                JSONObject obj = JSON.parseObject(item.toString());
                                id = obj.get("id").toString();
                                continue;
                            }
                        }
                    }
                    return id;
                }
                return "";
            } else {
                return "";
            }
        }catch (Exception ex){
            LOGGER.info("getMarketingAccount",ex);
            throw GlobalException.build("绑定融媒号失败");
        }
    }
}
